package com.blustreaksw.cyclecoach.history;

import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.UUID;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.text.SpannableString;
import android.text.format.DateFormat;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.blustreaksw.cyclecoach.MainActivity;
import com.blustreaksw.cyclecoach.UserProfileActivity;

import com.blustreaksw.cyclecoach.R;
import com.blustreaksw.cyclecoach.export.DropboxConnector;
import com.blustreaksw.cyclecoach.service.CycleCoachService;
import com.blustreaksw.cyclecoach.util.ConfirmationDialogFragment;


/* WorkoutLogEntryFragment
 * 
 * Creates for display the workout log entry view that was selected by the user
 * from WorkoutHistoryListFragment.
 * 
 */
public class WorkoutLogEntryFragment extends Fragment {
	public static final String EXTRA_WORKOUT_ENTRY_ID = "com.blustreaksw.cyclecoach.WORKOUT_ENTRY_ID";
	public static final String EXTRA_WORKOUT_SESSION_ID = "com.blustreaksw.cyclecoach.WORKOUT_SESSION_ID";
	private static final double KM_TO_MILES = 0.621371;
	
	WorkoutLogEntry mLogEntry;
	TextView mWorkoutLogEntry_date;
	TextView mWorkoutLogEntry_time_elapsed;
	TextView mWorkoutLogEntry_watts_avg;
	TextView mWorkoutLogEntry_watts_max;
	TextView mWorkoutLogEntry_nPower;
	TextView mWorkoutLogEntry_iFactor;
	TextView mWorkoutLogEntry_tss;
	TextView mWorkoutLogEntry_heart_rate_avg;
	TextView mWorkoutLogEntry_heart_rate_max;
	TextView mWorkoutLogEntry_cadence_avg;
	TextView mWorkoutLogEntry_cadence_max;
	TextView mWorkoutLogEntry_speed_avg;
	TextView mWorkoutLogEntry_speed_max;
	TextView mWorkoutLogEntry_distance;
	TextView mWorkoutLogEntry_calories;
	
	private boolean mHistoryActivity;
	private int mSessionId;
	
	
    public static WorkoutLogEntryFragment newInstance(UUID logEntryId) {
        Bundle args = new Bundle();
        args.putSerializable(EXTRA_WORKOUT_ENTRY_ID, logEntryId);

        WorkoutLogEntryFragment fragment = new WorkoutLogEntryFragment();
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_workout_log_entry, parent, false);
        
        mSessionId = getArguments().getInt(CycleCoachService.EXTRA_SESSION_ID, -1);
        if(mSessionId >= 0) {
        	mLogEntry = WorkoutHistoryContainer.getInstance(getActivity()).getLogEntry(mSessionId);
        } else {
	        UUID logEntryId = (UUID)getArguments().getSerializable(EXTRA_WORKOUT_ENTRY_ID);
	        mLogEntry = WorkoutHistoryContainer.getInstance(getActivity()).getLogEntry(logEntryId);
        }
        
        if(mLogEntry.getLogEntryCount() == 0) {
        	mHistoryActivity = false;
        	getActivity().getActionBar().setDisplayHomeAsUpEnabled(false);
            getActivity().getActionBar().setHomeButtonEnabled(false);
            getActivity().getActionBar().setTitle("Workout Summary");
            getActivity().getActionBar().setSubtitle(null);
        } else {
        	mHistoryActivity = true;
        	getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
        }
        
        getActivity().setTitle(R.string.subactivity_workoutLogEntry_title);
        setHasOptionsMenu(true);
        
        mLogEntry.setTitle(getString(R.string.workoutLogEntry_title));
        
        TextView resultCountView = (TextView)v.findViewById(R.id.resultCountView);
        if(mLogEntry.getLogEntryCount() == 0) {
        	resultCountView.setText("");
        	((TextView)v.findViewById(R.id.swipeForNextLabel)).setText("");
        	
        } else {
        	resultCountView.setText("Entry " + Integer.toString(mLogEntry.getLogEntryNumber()) 
        			+ " of " + Integer.toString(mLogEntry.getLogEntryCount()));
        }
        
        mWorkoutLogEntry_date = (TextView) v.findViewById(R.id.workoutLogEntryValue_date);
        
        String format = new String("cccc MMM dd, yyyy hh:mma z");
        SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.US);
        SpannableString dateString = new SpannableString(String.format("%s", dateFormat.format(mLogEntry.getDate())));
        dateString.setSpan(new UnderlineSpan(), 0, dateString.length(), 0);
        mWorkoutLogEntry_date.setText(dateString);
        
        mWorkoutLogEntry_time_elapsed = (TextView) v.findViewById(R.id.workoutLogEntryValue_time_elapsed);
        if(mLogEntry.getTimeElapsed() >= 3600000) {
        	mWorkoutLogEntry_time_elapsed.setText(String.format("%d:%02d:%02d.%d", 
        			mLogEntry.getTimeElapsed() / 3600000, 
        			(mLogEntry.getTimeElapsed() % 3600000) / 60000,
        			(mLogEntry.getTimeElapsed() % 60000) / 1000,
        			mLogEntry.getTimeElapsed() % 1000));
        } else {
        	mWorkoutLogEntry_time_elapsed.setText(String.format("%02d:%02d.%d", 
        			(mLogEntry.getTimeElapsed() % 3600000) / 60000,
        			(mLogEntry.getTimeElapsed() % 60000) / 1000,
        			mLogEntry.getTimeElapsed() % 1000));
        }
    	mWorkoutLogEntry_watts_avg = (TextView) v.findViewById(R.id.workoutLogEntryValue_watts_avg);
    	if(mLogEntry.getWattsAvg() > 0) {
    		mWorkoutLogEntry_watts_avg.setText(Integer.toString(mLogEntry.getWattsAvg()));
    	}
    	
    	mWorkoutLogEntry_watts_max = (TextView) v.findViewById(R.id.workoutLogEntryValue_watts_max);
    	if(mLogEntry.getWattsMax() > 0) {
    		mWorkoutLogEntry_watts_max.setText(Integer.toString(mLogEntry.getWattsMax()));
    	}
    	
    	mWorkoutLogEntry_nPower = (TextView) v.findViewById(R.id.workoutLogEntryValue_nPower);
    	if(mLogEntry.getNominalPower() > 0) {
    		mWorkoutLogEntry_nPower.setText(Integer.toString(mLogEntry.getNominalPower()));
    	}
    	
    	mWorkoutLogEntry_iFactor = (TextView) v.findViewById(R.id.workoutLogEntryValue_iFactor);
    	if(mLogEntry.getIFactor() > 0) {
    		mWorkoutLogEntry_iFactor.setText(String.format("%1.2f", mLogEntry.getIFactor()));
    	}
    	
    	mWorkoutLogEntry_tss = (TextView) v.findViewById(R.id.workoutLogEntryValue_tss);
    	if(mLogEntry.getTSS() > 0) {
    		mWorkoutLogEntry_tss.setText(String.format("%1.2f", mLogEntry.getTSS()));
    	}
    	
    	mWorkoutLogEntry_heart_rate_avg = (TextView) v.findViewById(R.id.workoutLogEntryValue_heart_rate_avg);
    	if(mLogEntry.getHeartRateAvg() > 0) {
    		mWorkoutLogEntry_heart_rate_avg.setText(Integer.toString(mLogEntry.getHeartRateAvg()));
    	}
    	
    	mWorkoutLogEntry_heart_rate_max = (TextView) v.findViewById(R.id.workoutLogEntryValue_heart_rate_max);
    	if(mLogEntry.getHeartRateMax() > 0) {
    		mWorkoutLogEntry_heart_rate_max.setText(Integer.toString(mLogEntry.getHeartRateMax()));
    	}
    	
    	mWorkoutLogEntry_cadence_avg = (TextView) v.findViewById(R.id.workoutLogEntryValue_cadence_avg);
    	if(mLogEntry.getCadenceAvg() > 0) {
    		mWorkoutLogEntry_cadence_avg.setText(Integer.toString(mLogEntry.getCadenceAvg()));
    	}
    	
    	mWorkoutLogEntry_cadence_max = (TextView) v.findViewById(R.id.workoutLogEntryValue_cadence_max);
    	if(mLogEntry.getCadenceMax() > 0) {
    		mWorkoutLogEntry_cadence_max.setText(Integer.toString(mLogEntry.getCadenceMax()));
    	}
    	
    	mWorkoutLogEntry_speed_avg = (TextView) v.findViewById(R.id.workoutLogEntryValue_speed_avg);
    	if(mLogEntry.getSpeedAvg() > 0) {
    		if(WorkoutHistoryContainer.useMetricUnits()) {
    			mWorkoutLogEntry_speed_avg.setText(String.format("%1.2f kph", mLogEntry.getSpeedAvg()));
    		} else {
    			mWorkoutLogEntry_speed_avg.setText(String.format("%1.2f mph", mLogEntry.getSpeedAvg() * KM_TO_MILES));
    		}
    	}
    	
    	mWorkoutLogEntry_speed_max = (TextView) v.findViewById(R.id.workoutLogEntryValue_speed_max);
    	if(mLogEntry.getSpeedMax() > 0) {
    		if(WorkoutHistoryContainer.useMetricUnits()) {
    			mWorkoutLogEntry_speed_max.setText(String.format("%1.2f kph", mLogEntry.getSpeedMax()));
    		} else {
    			mWorkoutLogEntry_speed_max.setText(String.format("%1.2f mph", mLogEntry.getSpeedMax() * KM_TO_MILES));
    		}
    	}
    	
    	mWorkoutLogEntry_distance = (TextView) v.findViewById(R.id.workoutLogEntryValue_distance);
    	if(mLogEntry.getDistanceTraveled() > 0) {
    		if(WorkoutHistoryContainer.useMetricUnits()) {
    			mWorkoutLogEntry_distance.setText(String.format("%1.2f km", mLogEntry.getDistanceTraveled()));
    		} else {
    			mWorkoutLogEntry_distance.setText(String.format("%1.2f miles", mLogEntry.getDistanceTraveled() * KM_TO_MILES));
    		}
    	}
    	
    	mWorkoutLogEntry_calories = (TextView) v.findViewById(R.id.workoutLogEntryValue_calories);
    	if(mLogEntry.getCaloriesBurned() > 0) {
    		mWorkoutLogEntry_calories.setText(Integer.toString(mLogEntry.getCaloriesBurned()));
    	}
        return v;
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    	super.onCreateOptionsMenu(menu, inflater);
    	if(mHistoryActivity) {
    		inflater.inflate(R.menu.fragment_workout_log_entry, menu);
    	} else {
    		inflater.inflate(R.menu.fragment_workout_complete, menu);
    	}
    }
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    		case android.R.id.home:
    			if(mHistoryActivity) {
	    			if(NavUtils.getParentActivityName(getActivity()) != null) {
	    				NavUtils.navigateUpFromSameTask(getActivity());
	    			}
    			} else {
    				
    			}
    			return true;
    			
    		case R.id.workoutLogEntry_menuItem_discard:
				new ConfirmationDialogFragment().configureDialog(new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// Handle Ok
						WorkoutHistoryContainer.getInstance(getActivity()).deleteLogEntry(mLogEntry);
						if(mHistoryActivity) {
			    			if(NavUtils.getParentActivityName(getActivity()) != null) {
			    				NavUtils.navigateUpFromSameTask(getActivity());
			    			}
		    			} else {
		    				getActivity().getSupportFragmentManager().popBackStack();
		    			}
					}
				}, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						// Handle Cancel
						
					}
				}, "Delete this workout?", null, getActivity())
				.onCreateDialog(null).show();
    			return true;
    			
    		case R.id.workoutLogEntry_menuItem_save:
    			Toast.makeText(getActivity(), "Workout Saved", Toast.LENGTH_SHORT).show();
    			((MainActivity)getActivity()).getSupportFragmentManager().popBackStackImmediate();
    			return true;
    		
    		case R.id.workoutLogEntry_menuItem_share:
    			// Ask if user wants to upload results to the cloud
    			DropboxConnector dc = DropboxConnector.getInstance(getActivity());
    			if(dc.isLoggedIn()) {
    				dc.exportSessionDataToDropbox(mLogEntry.getSessionId(), getActivity());
    			} else {
    				Toast.makeText(getActivity(), "Not logged in", Toast.LENGTH_SHORT).show();
    			}
    			return true;
    		
    		default:
    			return super.onOptionsItemSelected(item); 
    	}
    }
    
    @Override
	public void onPrepareOptionsMenu(Menu menu) {
    	
    	if(mHistoryActivity == false) {
			menu.findItem(R.id.scanning_indicator).setActionView(R.layout.progress_indicator).setVisible(false);
			menu.findItem(R.id.action_createUserWizard_restartDeviceScan).setVisible(false);
			menu.findItem(R.id.action_history).setVisible(false);
			menu.findItem(R.id.action_changeUser).setVisible(false);
			menu.findItem(R.id.action_musicPlayerExternalLink).setVisible(false);
			menu.findItem(R.id.action_createUserWizard_cancelButton).setVisible(false);
		}
	}
    
    @Override
    public void onResume() {
    	super.onResume();
    	getActivity().invalidateOptionsMenu();
    }
	
}
